package com.enation.app.javashop.seller.api.account;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.dag.eagleshop.core.account.model.dto.bankcard.BankCardDTO;
import com.dag.eagleshop.core.account.model.dto.bankcard.QueryBankCardDTO;
import com.dag.eagleshop.core.account.model.dto.base.PageDTO;
import com.dag.eagleshop.core.account.model.dto.base.ViewPage;
import com.dag.eagleshop.core.account.model.dto.member.MemberDTO;
import com.dag.eagleshop.core.account.model.dto.withdraw.*;
import com.dag.eagleshop.core.account.model.enums.WithdrawAccountTypeEnum;
import com.dag.eagleshop.core.account.model.enums.WithdrawTypeEnum;
import com.dag.eagleshop.core.account.model.vo.ApplyWithdrawReqVO;
import com.dag.eagleshop.core.account.service.AccountManager;
import com.dag.eagleshop.core.account.service.BankCardManager;
import com.enation.app.javashop.core.base.model.enums.YesNoEnum;
import com.enation.app.javashop.core.base.model.vo.SmsSendVO;
import com.enation.app.javashop.core.base.rabbitmq.AmqpExchange;
import com.enation.app.javashop.core.member.model.dos.Member;
import com.enation.app.javashop.core.member.service.MemberManager;
import com.enation.app.javashop.core.shop.model.dos.ShopDetailDO;
import com.enation.app.javashop.core.shop.service.ShopManager;
import com.enation.app.javashop.framework.context.UserContext;
import com.enation.app.javashop.framework.security.model.Seller;
import com.enation.app.javashop.framework.util.EnvironmentUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import springfox.documentation.annotations.ApiIgnore;

import javax.validation.Valid;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * 提现控制器
 * @author 孙建
 */
@Api(description = "提现接口模块")
@RestController
@RequestMapping("/account/withdraw")
public class WithdrawController {

    @Autowired
    private MemberManager memberManager;
    @Autowired
    private AccountManager accountManager;
    @Autowired
    private BankCardManager bankCardManager;
    @Autowired
    private ShopManager shopManager;
    @Autowired
    private AmqpTemplate amqpTemplate;


    @PostMapping("/queryWithdrawAcount")
    @ApiOperation(value = "查询提现账号信息")
    public Map<String, Object> queryWithdrawAcount() {
        Seller seller = UserContext.getSeller();
        if (ObjectUtils.isEmpty(seller)) {
            throw new RuntimeException("商户登录异常");
        }
        String accountMemberId = this.getAccountMemberId(seller.getUid());

        // 查询支付宝
        QueryWithdrawAccountDTO queryWithdrawAccountDTO = new QueryWithdrawAccountDTO();
        queryWithdrawAccountDTO.setMemberId(accountMemberId);
        queryWithdrawAccountDTO.setType(WithdrawAccountTypeEnum.ALIPAY.getIndex());
        ViewPage<WithdrawAccountDTO> withdrawAccountViewPage = accountManager.queryWithdrawAccountList(new PageDTO<>(1, 1, queryWithdrawAccountDTO));
        List<WithdrawAccountDTO> withdrawAccountList = withdrawAccountViewPage.getRecords();

        // 查询银行卡
        QueryBankCardDTO queryBankCardDTO = new QueryBankCardDTO();
        queryBankCardDTO.setMemberId(accountMemberId);
        PageDTO<QueryBankCardDTO> pageDTO = new PageDTO<>(1, 1, queryBankCardDTO);
        ViewPage<BankCardDTO> bankCardViewPage = bankCardManager.queryList(pageDTO);
        List<BankCardDTO> bankCardList = bankCardViewPage.getRecords();

        // 如果是企业账户银行卡，设置开户行省市
        BankCardDTO bankCardDTO = null;
        if (bankCardList != null && bankCardList.size() > 0) {
            bankCardDTO = JSON.parseObject(JSON.toJSON(bankCardList.get(0)).toString(), new TypeReference<BankCardDTO>() {});
            if (YesNoEnum.YES.getIndex() == bankCardDTO.getBankCardType()) {
                ShopDetailDO shopDetail = shopManager.getShopDetail(seller.getSellerId());
                bankCardDTO.setBankProvince(shopDetail.getBankProvince());
                bankCardDTO.setBankCity(shopDetail.getBankCity());
                bankCardDTO.setBankProvinceId(shopDetail.getBankProvinceId());
                bankCardDTO.setBankCityId(shopDetail.getBankCityId());
            }
        }

        // 封装返回值
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("alipayWithdrawAccount", withdrawAccountList != null && withdrawAccountList.size() > 0 ? withdrawAccountList.get(0) : null);
        resultMap.put("bankCard", bankCardList != null && bankCardList.size() > 0 ? bankCardList.get(0) : null);
        resultMap.put("webBankCard", bankCardDTO);
        return resultMap;
    }


    @ApiOperation(value = "申请提现", notes = "申请提现")
    @PostMapping(value = "applyWithdraw")
    public ApplyWithdrawRespDTO applyWithdraw(@Valid @RequestBody ApplyWithdrawReqVO applyWithdrawReqVO) {
        Integer uid = UserContext.getSeller().getUid();
        String accountMemberId = this.getAccountMemberId(uid);
        // 查询账户会员
        MemberDTO memberDTO = accountManager.queryMemberById(accountMemberId);
        String memberName = "【商户】"+memberDTO.getMemberName();
        // 申请提现
        ApplyWithdrawReqDTO applyWithdrawReqDTO = new ApplyWithdrawReqDTO();
        BeanUtils.copyProperties(applyWithdrawReqVO, applyWithdrawReqDTO);
        applyWithdrawReqDTO.setMemberId(memberDTO.getId());
        applyWithdrawReqDTO.setMemberName(memberName);
        Integer withdrawType = applyWithdrawReqVO.getWithdrawType();
        applyWithdrawReqDTO.setWithdrawType(withdrawType == null ? WithdrawTypeEnum.OFFLINE.getIndex() : withdrawType);
        String applyRemark = applyWithdrawReqVO.getApplyRemark();
        applyWithdrawReqDTO.setApplyRemark(StringUtils.isEmpty(applyRemark) ? "申请提现" : applyRemark);
        ApplyWithdrawRespDTO applyWithdrawRespDTO = accountManager.applyWithdraw(applyWithdrawReqDTO);
        // 数据保存成功 并且是生产环境发短息
        if (applyWithdrawRespDTO.isSuccess() && EnvironmentUtils.isProd()) {
            SmsSendVO smsSendVO = new SmsSendVO();
            smsSendVO.setContent("收到一个新的提现申请，流水号:" + applyWithdrawRespDTO.getWithdrawNo() + "，请及时处理。");
            smsSendVO.setMobile("15960179760");// 罗秋菊手机号
            //发送短信
            amqpTemplate.convertAndSend(AmqpExchange.SEND_MESSAGE, AmqpExchange.SEND_MESSAGE + "_QUEUE",
                    smsSendVO);
        }
        return applyWithdrawRespDTO;
    }

    @PostMapping("/queryWithdrawList")
    @ApiOperation(value = "查询提现记录")
    public ViewPage<WithdrawBillDTO> queryWithdrawList(@ApiIgnore Integer pageNo, @ApiIgnore Integer pageSize) {
        Integer uid = UserContext.getSeller().getUid();
        String accountMemberId = this.getAccountMemberId(uid);

        QueryWithdrawBillDTO queryWithdrawBillDTO = new QueryWithdrawBillDTO();
        queryWithdrawBillDTO.setMemberId(accountMemberId);

        PageDTO<QueryWithdrawBillDTO> pageDTO = new PageDTO<>();
        pageDTO.setPageNum(pageNo);
        pageDTO.setPageSize(pageSize);
        pageDTO.setBody(queryWithdrawBillDTO);
        return accountManager.queryWithdrawList(pageDTO);
    }

    /**
     * 获取账户会员id
     */
    private String getAccountMemberId(Integer uid){
        Member member = memberManager.getModel(uid);
        return member.getAccountMemberId();
    }

}
